import config from '@/common/environment.js';
const WEBSOCKET_SERVICE = config.WEBSOCKET_SERVICE;
var webScoket = {};

//初始话
function connectSocketInit(userId,chatGroupId) {
	let url = WEBSOCKET_SERVICE + userId + "/" + chatGroupId;
	console.log("webSocket链接地址:" , url);
	webScoket.socketTask = uni.connectSocket({
		url: url,
		success(data) {
			console.log("websocket初始化连接成功");
		},
	});
}

//消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】	
function onMessage() {
		webScoket.socketTask.onOpen((res1) => {
			webScoket.socketTask.onMessage((msg) => {
				console.log("websocket接收信息",msg);
				return msg;
			});
		})
}

//点击发送信息到后台服务器
function  sendMsg(msg) {
    webScoket.socketTask.onOpen((res) => {
        webScoket.socketTask.send({
			data: JSON.stringify(msg),
		    async success() {
				console.log("webscoket发送信息成功");
		    },
		    fail() {
				uni.showToast({
					duration: 2000,
					title: '网络不佳，发送失败',
					icon: 'none'
				})
		    }
		});
    })
}

// 这里仅是事件监听【如果socket关闭了会执行】
function onClose() {
	webScoket.socketTask.onClose(() => {
		console.log("监听到websocket已经断开连接");
		
	})
}

// 关闭websocket【离开这个页面的时候执行关闭】
function closeSocket() {
	webScoket.socketTask.close({
		success(res) {
			console.log("关闭websocket成功", res)
		},
		fail(err) {
			console.log("关闭webscoket失败", err);
			webScoket.socketTask=null;
		}
	})
}

function getUnReadMsg(){
      let userId=service.getUsers().id;
      let param={"userId":userId};
      api.chatGroup.countUnreadNum(param).then(res=>{
        console.log("websocket监听未读信息数量响应结果",res);
        if(res.code==1){
          let unReadMsg="0";
          if(res.data>99){
            unReadMsg='99+';
          }else{
            unReadMsg=res.data+'';
          }
          if(res.data===0){
            uni.removeTabBarBadge({
              index:1
            });
            plus.runtime.setBadgeNumber(-1);
          }else{
            uni.setTabBarBadge({
              index: 1,
              text: unReadMsg.toString()
            })
            plus.runtime.setBadgeNumber(unReadMsg);
          }
        }else{
          console.log("请求未读信息数量接口出现异常");
        }
      });
}

export default {
  connectSocketInit,
  closeSocket,
  sendMsg,
  onMessage
}	
